﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Core.DatabaseHelpers;
using Core.Interfaces;
using Core.Interfaces.IDAO;
using Core.Unity;
using Microsoft.Practices.Unity;
namespace Core.DAO
{
    class OwnedBuildingDAO : AbstractDAO<IOwnedBuilding>,IOwnedBuildingDAO
    {
        public OwnedBuildingDAO(IConnection connection) : base(connection)
        {
        }

        public virtual bool Delete(IDomainObject domainObject)
        {
            bool result = false;
          
            var ob = (IOwnedBuilding) domainObject;
            var s = string.Format(" delete from owned_building where register_id={0} AND id_action={1}", ob.RegId,
                                  ob.Action.ActionId);
            try
            {
                Connection.ExecuteQuery(s);
                result = true;
            }
            catch (Exception exception)
            {
                System.Data.SqlClient.SqlException e = (SqlException)exception;

                MessageBox.Show(domainObject.GetErrorByCode(e.Number), "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error,
                                MessageBoxDefaultButton.Button1);
                Connection.CloseConnection();

            }


            return result;
        }
       

        protected override void GetDependendModels(object domainobject, object[] row)
        {
            var ownedBuilding = (IOwnedBuilding) domainobject;
            var buildingDAO = ResolverContainer.Resolver.Resolve<IBuildingDAO>();
            var actionDAo = ResolverContainer.Resolver.Resolve<IActionDAO>();
            var customerDAO = ResolverContainer.Resolver.Resolve<ICustomerDAO>();
            ownedBuilding.Building = buildingDAO.GetAll(true).First(x=>x.RegisterID == row[0].ToString());
            ownedBuilding.Action = actionDAo.GetAll(false).First(x=> x.ActionId == int.Parse(row[1].ToString()));
            ownedBuilding.Customer = customerDAO.GetAll(false).First(x => x.CustomerID == int.Parse(row[2].ToString()));
        }
    }
}
